package com.mall.manager.authority.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.mall.untils.Page;
import com.mall.untils.StringUtil;

/**
 * 权限业务
 * 
 * @ClassName: PowerService
 * @Description:
 * @author:wangwenyue wangwenyue@ide365.com
 * @date 2016年7月7日 下午2:54:13
 */
@Service
public class PowerService {

	private Logger logger = LoggerFactory.getLogger(PowerService.class);

	@Resource
	private JdbcTemplate jdbcTemplate;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	public Page queryPagelist(Map<String, Object> paraMap) {
		Page page = null;
		List<Map<String, Object>> queryForList = null;
		int pageNo = MapUtils.getIntValue(paraMap, "currentpageno");
		String name = MapUtils.getString(paraMap, "name");
		int pageSize = 10;
		Integer total =0;
		try {
			if (pageNo == 0) {
				pageNo = 1;
			}
			StringBuffer sqlCount = new StringBuffer("select count(*) from t_power where 1=1 ");
			if (StringUtils.isNotBlank(name)) {
				name = StringUtil.getByteToString(name);
				sqlCount.append("and name like ? ");
				total = jdbcTemplate.queryForObject(sqlCount.toString(), Integer.class,"%"+name+"%");
			}else{
				total = jdbcTemplate.queryForObject(sqlCount.toString(), Integer.class);
			}
			
			int startIndex = Page.getStartOfPage(pageNo, pageSize);
			StringBuffer sql = new StringBuffer("select * from t_power where 1=1 ");

			if (StringUtils.isNotBlank(name)) {
				sql.append("and name like ? ");
			}

			String sqlbf = sql.append(" order by id desc limit " + startIndex + "," + pageSize).toString();
			if (StringUtils.isNotBlank(name)) {
				queryForList = jdbcTemplate.queryForList(sqlbf, "%"+name+"%");
			}else{
				
				queryForList = jdbcTemplate.queryForList(sqlbf);
			}
			page = new Page(startIndex, total, pageSize, queryForList);
			return page;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.toString());
			return null;
		}
	}
	
	
	/**
	 * 根据条件（数据库列名）获取详细权限
	 * @param paraMap条件值
	 * @param claim 条件名称
	 * @return
	 */
	public Map<String, Object> getPowerByclaim(Map<String, Object> paraMap) {
		String claim = MapUtils.getString(paraMap, "claim");
		String res = MapUtils.getString(paraMap, "res");
		String sql = "select * from t_power where " + claim + " = ? limit 0,1";
		try {
			Map<String, Object> map = jdbcTemplate.queryForMap(sql, res);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("errorWWY===>>getPowerByclaim()");
			return null;
		}
	}

	/**
	 * 添加权限
	 * @return
	 */
	public int addPower(Map<String, Object> paraMap) {
		String parentId = MapUtils.getString(paraMap, "parentId");
		String id = MapUtils.getString(paraMap, "id");
		String name = MapUtils.getString(paraMap, "name");
		String poweraddr = MapUtils.getString(paraMap, "poweraddr");
		String level = MapUtils.getString(paraMap, "level");
		String remarks = MapUtils.getString(paraMap, "remarks");
		
		if(StringUtils.isBlank(parentId)){
			parentId="0";
		}
		String sql = "insert into t_power(parent_id,name,poweraddr,level,remarks,create_time,update_time) values(?,?,?,?,?,now(),now())";
		if(StringUtils.isNotBlank(id)&& !"null".equals(id)){
			 sql = "update t_power set parent_id=?,name=?,poweraddr=?,level=?,remarks=?,update_time=now() where id=?";
		}
		try {
			if(StringUtils.isNotBlank(id)&& !"null".equals(id)){
				 sql = "update t_power set parent_id=?,name=?,poweraddr=?,level=?,remarks=?,update_time=now() where id=?";
				 return jdbcTemplate.update(sql, parentId,
							StringUtil.getByteToString(name), poweraddr, level,
							StringUtil.getByteToString(remarks),id);
			}else{
				return	jdbcTemplate.update(sql, parentId,
						StringUtil.getByteToString(name), poweraddr, level,
						StringUtil.getByteToString(remarks));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("errorWWY===>>addPower()");
			return 0;
		}
	}

	/**
	 * 删除权限
	 * 
	 * @param paraMap
	 * @return
	 */
	public int removePower(Map<String, Object> paraMap) {

		// TODO 删除前查找有没有与角色绑定的，如果有不能删除，没有才能删除

		int id = MapUtils.getIntValue(paraMap, "id");
		try {
			String sql = "delete from t_power where id=?";
			return jdbcTemplate.update(sql, id);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("errorWWY===>>removePower()");
			return 0;
		}
	}

	/**
	 * 修改权限
	 * 
	 * @param paraMap
	 * @return
	 */
	public int updatePower(Map<String, Object> paraMap) {
		String id = MapUtils.getString(paraMap, "id");
		String parentId = MapUtils.getString(paraMap, "parentId");
		String name = MapUtils.getString(paraMap, "name");
		String poweraddr = MapUtils.getString(paraMap, "poweraddr");
		String level = MapUtils.getString(paraMap, "level");
		String remarks = MapUtils.getString(paraMap, "remarks");
		String sql = "update  t_power set parent_id=?,name=?,poweraddr=?,level=?,remarks=?,update_time=now() where id=?";

		try {
			return jdbcTemplate.update(sql, parentId,
					StringUtil.getByteToString(name), poweraddr, level,
					StringUtil.getByteToString(remarks), id);
		} catch (Exception e) {
			logger.info("errorWWY===>>updatePower()");
			e.printStackTrace();
			return 0;
		}

	}

	/**
	 * 根据级别获取父级别所有权限
	 * @param string
	 * @return
	 */
	public List<Map<String, Object>> getParent(String level) {
		String sql = "select * from t_power where level="+level;
		try {
			return jdbcTemplate.queryForList(sql);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.toString());
		}
		return null;
	}
	
	
	/**
	 * 根据等级查询所有权限
	 * @param paraMap
	 * @return
	 */
	public List<Map<String, Object>> searchlistpower(int level) {
		//String sql = "select * from t_power where level = '" + level + "'";
//		String sql = "select t.id,t.name as pname,t.level as plevel, p.parent_id,p.name,p.level from  "
//				+ "(select id, `name`,`level` from t_power ) as t,t_power p where t.id = p.parent_id and t.level ='"+level+"'";
//		if(level == 1){
//			sql = "select DISTINCT t.id,t.name as pname,t.level as plevel from  (select id, `name`,`level` from t_power ) as t,"
//					+ "t_power p where t.id = p.parent_id  and t.level = '"+ level + "'";			
//		}else if(level == 2){
//			sql = "select t.id,t.name as pname,t.level as plevel,p.id as pid, p.parent_id,p.name as sname,p.level as slevel from  "
//					+ "(select id, `name`,`level` from t_power ) as t,t_power p where t.id = p.parent_id  and t.level = '"+level+"'";
//		}
		
		String sql="select * from t_power where level='"+level+"'";
		List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        return rs;
	}

}
